# -*- coding: utf-8 -*-
# @Time    : 2021/11/8 17:41
# @Author  : ydh
# @File    : serializer.py
# @Software: PyCharm
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from apps.book.models.AuthorInfo import AuthorInfo
from apps.book.models.BookInfo import BookInfo
from apps.book.models.CategoryInfo import CategoryInfo
from apps.book.models.PubHouse import PubHouse


# 图书序列化器
class BookInfoReadSerializer(ModelSerializer):
    book_author = serializers.SerializerMethodField()
    book_translator = serializers.SerializerMethodField()

    class Meta:
        model = BookInfo
        fields = "__all__"

    def get_book_author(self, obj):
        book_author = []
        try:
            for obj in obj.book_author.all():
                book_author.append(
                    {
                        "id": obj.id,
                        "name": obj.author_name,
                        "author_nationality": obj.author_nationality,
                        "author_desc": obj.author_desc
                    }
                )
            return book_author
        except ObjectDoesNotExist:
            return

    def get_book_translator(self, obj):
        book_author = []
        try:
            for obj in obj.book_translator.all():
                book_author.append(
                    {
                        "id": obj.id,
                        "name": obj.author_name,
                        "author_nationality": obj.author_nationality,
                        "author_desc": obj.author_desc
                    }
                )
            return book_author
        except ObjectDoesNotExist:
            return


class BookInfoCreateSerializer(ModelSerializer):
    class Meta:
        model = BookInfo
        fields = "__all__"


# 作者，译者序列化器
class AuthorInfoReadSerializer(ModelSerializer):
    class Meta:
        model = AuthorInfo
        fields = "__all__"


class AuthorInfoCreateSerializer(ModelSerializer):
    class Meta:
        model = AuthorInfo
        fields = "__all__"


# 图书类型序列化器
class CategoryInfoReadSerializer(ModelSerializer):
    class Meta:
        model = CategoryInfo
        fields = "__all__"


# 出版社序列化器
class PubHouseInfoReadSerializer(ModelSerializer):
    class Meta:
        model = PubHouse
        fields = "__all__"


class PubHouseInfoCreateSerializer(ModelSerializer):
    class Meta:
        model = PubHouse
        field = "__all__"
